package com.example.springsecuritydemo.handler;

import com.example.springsecuritydemo.costant.ResultCode;
import com.example.springsecuritydemo.support.RestResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author by linenxi
 * @Classname NoAuthHandler
 * @Description
 * @Date 2019/5/10
 */
@Component
public class NoAuthHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        RestResult<Object> result = new RestResult<Object>();
        result.setCode(ResultCode.UN_AUTHORIZED_ACCESS.getCode());
        result.setMessage(ResultCode.UN_AUTHORIZED_ACCESS.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }

}
